package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Override
    @Transactional
    public ShoppingCart addShoppingCart(ShoppingCart shoppingCart, Long userId) {
//        boolean flag=service.save(shoppingCart);
        //添加购物车数量 判断购物车是否已有该菜品/套餐 如果没有  则视为1 如果有在在原有 菜品/套餐 数值+1
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId());
        shoppingCartLambdaQueryWrapper.eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart dishOrSetmeal=this.getOne(shoppingCartLambdaQueryWrapper);

        if(dishOrSetmeal !=null){
            //购物车已存在 则数量+1 更新购物车数据
            dishOrSetmeal.setNumber(dishOrSetmeal.getNumber()+1);
            this.updateById(dishOrSetmeal);
            return dishOrSetmeal;
        }
        //不存在 则设置初始数量为
        shoppingCart.setNumber(1);
        shoppingCart.setUserId(userId);
        shoppingCart.setCreateTime(LocalDateTime.now());
        this.save(shoppingCart);
        return shoppingCart;
    }
}
